<?php
/**	
*	FILENAME: 		/libraries/users.php
*	DESCRIPTION:	This library contains and returns information related MyNova Mobile user records.
*	AUTHOR:			Casey Burkhardt
*	VERSION:		1.0.0
*	LAST MODIFIED:	12/31/2009
**/

require_once($_SERVER['DOCUMENT_ROOT'] . "/libraries/database.php");

/**	
*	DESCRIPTION:	Returns the `users`.`uid` value of a user record given an LDAP username.
**/
function getUserIDValue($ldapUsername) {
	connectToDatabase();
	$sql = "SELECT *
			FROM `users`
			WHERE `ldap_username` = '" . $ldapUsername . "';";
	$result = mysql_query($sql) or die(mysql_error());
	if (mysql_num_rows($result) > 0) {
		while ($row = mysql_fetch_assoc($result)) {
			return $row["uid"];
		}
	} else {
		return FALSE;
	}	
}

/**	
*	DESCRIPTION:	Returns the LDAP username of a user record given a `users`.`uid` value.
**/
function getLDAPUsername($uid) {
	connectToDatabase();
	$sql = "SELECT *
			FROM `users`
			WHERE `uid` = '" . $uid . "';";
	$result = mysql_query($sql) or die(mysql_error());
	if (mysql_num_rows($result) > 0) {
		while ($row = mysql_fetch_assoc($result)) {
			return $row["ldap_username"];
		}
	} else {
		return FALSE;
	}	
}

/**
*	DESCRIPTION:	Adds a new user to the database.
**/
function addNewRegisteredUser($username, $encryptedPin, $UDID) {
	$registrationDate = date("Y-m-d H:i:s");
	
	connectToDatabase();
	
	$sqlQuery = "INSERT 
				 INTO `users` (ldap_username, pin_hash, registration_date)
				 VALUES ('". $username . "', '" . $encryptedPin . "', '" . $registrationDate . "');";
	if (mysql_query($sqlQuery) === FALSE) {
		die(mysql_error());
		return FALSE;
	}
	
	
	$sqlQuery = "SELECT *
				 FROM `users`
				 WHERE `ldap_username` = '" . $username . "';";
	$result = mysql_query($sqlQuery);
	if ($result === FALSE) {
		return FALSE;	
	}
	$resultArray = mysql_fetch_assoc($result);
	if ($resultArray === FALSE) {
		return FALSE;	
	}
	
	$uid = $resultArray["uid"];
	
	$sqlQuery = "INSERT 
				 INTO `devices` (uid, udid, primary_device)
				 VALUES ('" . $uid . "', '" . $UDID . "', '" . 1 . "');";
	if (mysql_query($sqlQuery) === FALSE) {
		return FALSE;
	}
	
	return $uid;	
}

/**
 *	DESCRIPTION:	Returns an encrypted pin.
**/
function encryptPin($pin) {
	return  md5($pin . getPINSalt());
}

/**
 *	DESCRIPTION:	Verifies a user's PIN given their specific UID and encrypted PIN.
**/
function authenticatePIN($uid, $encryptedPin) {
	connectToDatabase();
	$sqlQuery = "SELECT *
				 FROM `users`
				 WHERE `uid` = '" . $uid . "' 
				 AND `pin_hash` = '" . $encryptedPin . "';";
	$result = mysql_query($sqlQuery);
	if ($result === FALSE) {
		return FALSE;	
	}
	if (mysql_num_rows($result) != 0) {
		return TRUE;	
	} else {
		return FALSE;	
	}
}

?>